package com.itqf.config;

import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.lite.spring.api.SpringJobScheduler;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperConfiguration;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import com.itqf.job.MyElasticJob;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2021/1/7
 * @Time: 上午9:45
 */
@Configuration
public class ElasticJobConfig {

    @Value("${registerCenter.serverList}")
    private  String  severList;
    @Value("${registerCenter.namespace}")
    private  String  namespace;

    @Value("${simpleJob.cron}")
    private  String  cron;
    @Value("${simpleJob.shardingTotalCount}")
    private  int  count;
    @Value("${simpleJob.jobName}")
    private  String  jobName;
    //shardingItemParameters
    @Value("${simpleJob.shardingItemParameters}")
    private  String  shardingItemParameters;

    /**
     *第1步. 注册中心
     * @return
     */

    @Bean
    public ZookeeperRegistryCenter center(){

        ZookeeperRegistryCenter zookeeperRegistryCenter =
                new ZookeeperRegistryCenter(new ZookeeperConfiguration
                        (severList,namespace));

        zookeeperRegistryCenter.init();//初始化注册中心

        return  zookeeperRegistryCenter;
    }

    /**
     *
     * 第三步 触发定时任务
     */
    @Bean
    public SpringJobScheduler springJobScheduler(MyElasticJob myElasticJob,
                                                 ZookeeperRegistryCenter center){

        //String jobName, String cron, int shardingTotalCount
        JobCoreConfiguration coreConfig = JobCoreConfiguration.
                newBuilder(jobName,cron,count)
                .shardingItemParameters(shardingItemParameters).build();
        //1.SimpleJobConfiguration
        SimpleJobConfiguration jobConfiguration =
                new SimpleJobConfiguration(coreConfig,MyElasticJob.class.getCanonicalName());

        //2.构建LiteJobConfiguration
        LiteJobConfiguration configuration = LiteJobConfiguration
                .newBuilder(jobConfiguration).build();

        //3. ElasticJob elasticJob, CoordinatorRegistryCenter regCenter, LiteJobConfiguration jobConfig
        SpringJobScheduler springJobScheduler = new SpringJobScheduler(myElasticJob,
                center,configuration);

        //4. 初识化分布式定时任务
        springJobScheduler.init();
        return  springJobScheduler;
    }


}
